<template>
  <div class="container">
    <div class="search">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="">
          <el-input v-model="formInline.id" placeholder="请输入品牌商id"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="formInline.name" placeholder="请输入品牌商名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查找</el-button>
          <el-button type="primary" @click="" @click="addOpenDialog()">添加</el-button>
          <el-button type="primary" @click="exportAll">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="品牌商Id" width="180">
        </el-table-column>
        <el-table-column prop="name" label="品牌商名称" width="180">
        </el-table-column>
        <el-table-column prop="picUrl" label="品牌商图片">
          <template slot-scope="scope">
            <el-image @click="srcListAdd(scope.row)" v-if="scope.row.picUrl" style="width: 100px; height: 100px"
              :src="scope.row.picUrl" :preview-src-list="srcList">
            </el-image>
            <span v-else>加载失败</span>
          </template>
        </el-table-column>
        <el-table-column prop="desc" width="450" align="center" label="介绍">
        </el-table-column>
        <el-table-column prop="floorPrice" label="低价"> </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="editOpenDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination background="" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pageNumber" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <div class="dialogEdit">
      <el-dialog :title="title" :visible.sync="dialogVisibleEdit" width="40%">
        <el-form ref="editDialogForm" :model="editDialogForm" label-width="80px" :rules="editRule">
          <el-form-item label="品牌商名称" prop="name">
            <el-input v-model="editDialogForm.name"></el-input>
          </el-form-item>
          <el-form-item label="介绍">
            <el-input v-model="editDialogForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="品牌商图片">
            <el-upload class="avatar-uploader" action="/api/admin/storage/create" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="editDialogForm.picUrl" :src="editDialogForm.picUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="低价">
            <el-input v-model="editDialogForm.floorPrice"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleEdit = false">取 消</el-button>
          <el-button type="primary" @click="upDataEdit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="dialogAdd">
      <el-dialog :title="title" :visible.sync="dialogVisibleAdd" width="40%">
        <el-form ref="addDialogForm" :model="addDialogForm" label-width="80px" :rules="addRule">
          <el-form-item label="品牌商名称" prop="name">
            <el-input v-model="addDialogForm.name"></el-input>
          </el-form-item>
          <el-form-item label="介绍">
            <el-input v-model="addDialogForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="品牌商图片">
            <el-upload class="avatar-uploader" action="/api/admin/storage/create" :show-file-list="false"
              :on-success="handleAvatarSuccessEdit" :before-upload="beforeAvatarUploadEdit">
              <img v-if="addDialogForm.picUrl" :src="addDialogForm.picUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="低价">
            <el-input v-model="addDialogForm.floorPrice"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleAdd = false">取 消</el-button>
          <el-button type="primary" @click="upDataAdd">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  // import dayjs from "dayjs";
  import { downloadXlsx } from "../../units/ex";
  export default {
    data() {
      return {
        // 预览图片
        srcList: [],
        // 添加对话框表单
        addDialogForm: {
          desc: "",
          floorPrice: "",
          name: "",
          picUrl: "",
        },
        //添加校验
        addRule: {
          name: [
            { required: true, message: "请输入品牌商名称", trigger: "blur" },
          ],
        },
        //对话框标题
        title: "",
        //编辑对话框表
        editDialogForm: {
          addTime: "",
          deleted: "",
          desc: "",
          floorPrice: "",
          id: "",
          name: "",
          picUrl: "",
          preview: [],
          sortOrder: "",
          updateTime: "",
        },
        editRule: {
          name: [
            { required: true, message: "请输入品牌商名称", trigger: "blur" },
          ],
        },
        //编辑对话框控制
        dialogVisibleEdit: false,
        //添加对话框控制
        dialogVisibleAdd: false,
        //搜索
        formInline: {
          id: "",
          name: "",
        },
        //表格数据
        tableData: null,
        //分页
        pageNumber: 1,
        pageSize: 20,
        total: 0,
      };
    },
    methods: {
      //预览图片
      srcListAdd(row) {
        this.srcList.push(row.picUrl);
      },
      //导出
      exportAll() {
        let list = [];
        for (let i = 0; i < this.tableData.length; i++) {
          let obj = [
            this.tableData[i].id,
            this.tableData[i].name,
            this.tableData[i].picUrl,
            this.tableData[i].desc,
            this.tableData[i].floorPrice,
          ];
          list.push(obj);
        }
        downloadXlsx(list, "表.xlsx");
      },
      //删除行
      deleteRow(row) {
        this.$store.dispatch("shopping/brand_deleteRow", row).then((res) => {
          // console.log(res, "res");
          this.getTableData();
          this.$notify({
            title: "成功",
            message: "成功删除",
            type: "success",
          });
        });
      },
      //添加确定
      upDataAdd() {
        this.$refs["addDialogForm"].validate((valid) => {
          if (valid) {
            let data = this.addDialogForm;
            this.$store.dispatch("shopping/brand_addUpData", data).then((res) => {
              // console.log(res,'res')
              this.$notify({
                title: "成功",
                message: "成功添加",
                type: "success",
              });
              this.dialogVisibleAdd = false;
              this.getTableData();
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      //上传图片
      handleAvatarSuccess(res, file) {
        // console.log(res,'res')
        this.editDialogForm.picUrl = res.data.url;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
      //添加图片上传
      handleAvatarSuccessEdit(res, file) {
        // console.log(res,'res')
        this.addDialogForm.picUrl = res.data.url;
      },
      beforeAvatarUploadEdit(file) {
        const isJPG = file.type === "image/jpeg";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return isJPG && isLt2M;
      },
      //编辑确定
      upDataEdit() {
        this.title == "编辑";
        // console.log("点击确定");
        this.$refs["editDialogForm"].validate((valid) => {
          if (valid) {
            this.$store
              .dispatch("shopping/brand_editUpData", this.editDialogForm)
              .then((res) => {
                // console.log(res, "res");
                this.dialogVisibleEdit = false;
                this.$notify({
                  title: "成功",
                  message: "成功修改",
                  type: "success",
                });
                this.getTableData();
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      //增加打开对话框
      addOpenDialog() {
        this.dialogVisibleAdd = true;
        this.title = "创建";
      },
      //编辑打开对话框
      editOpenDialog(row) {
        // console.log(row,'row')
        this.dialogVisibleEdit = true;
        this.title = "编辑";
        //赋值
        this.editDialogForm.addTime = row.addTime;
        this.editDialogForm.deleted = row.deleted;
        this.editDialogForm.desc = row.desc;
        this.editDialogForm.floorPrice = row.floorPrice;
        this.editDialogForm.id = row.id;
        this.editDialogForm.name = row.name;
        this.editDialogForm.picUrl = row.picUrl;
        this.editDialogForm.sortOrder = row.sortOrder;
        this.editDialogForm.preview[0] = row.picUrl;
        // let formattedTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        // console.log(formattedTime,'time')
        this.editDialogForm.updateTime = row.updateTime;
      },
      //关闭对话框
      handleClose(done) {
        done();
      },
      //查找
      onSubmit() {
        let data = {
          page: this.pageNumber,
          limit: this.pageSize,
          id: this.formInline.id,
          name: this.formInline.name,
          sort: "add_time",
          order: "desc",
        };
        this.$store.dispatch("shopping/brand_getTableData", data).then((res) => {
          // console.log(res, "res");
          this.tableData = res.data.list;
          this.total = res.data.total;
        });
      },
      //分页
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.getTableData();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pageNumber = val;
        this.getTableData();
      },
      //初始化表格
      getTableData() {
        let data = {
          page: this.pageNumber,
          limit: this.pageSize,
          sort: "add_time",
          order: "desc",
        };
        this.$store.dispatch("shopping/brand_getTableData", data).then((res) => {
          // console.log(res, "res");
          this.tableData = res.data.list;
          this.total = res.data.total;
        });
      },
    },
    created() {
      this.getTableData();
    },
  };
</script>

<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .container::v-deep {
    .dialogEdit {
      .el-form-item {
        .el-form-item__label {
          width: 100px !important;
        }

        .el-form-item__content {
          margin-left: 100px !important;
        }
      }
    }

    .dialogAdd {
      .el-form-item {
        .el-form-item__label {
          width: 100px !important;
        }

        .el-form-item__content {
          margin-left: 100px !important;
        }
      }
    }
  }
</style>